$.ajax({
    url:"homepage/findTags",
    type: 'post',
    async:false,
    success: function(data) {
        var arr = data.data
        $("#shopCategory").empty();
        for (let i = 0; i < arr.length; i++) {
            $("#shopCategory").append("<option value='" + arr[i].id + "'>" + arr[i].tagName + "</option>");
        }

    }
})
    // 存储上传的图片
    let uploadedImages = [];
    let uploadedCertificates = [];

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
    // 为头像上传区域添加点击事件
    document.querySelector('.shop-avatar-large').addEventListener('click', function() {
        document.getElementById('avatarInput').click();
    });

    // 为图片上传区域添加点击事件
    document.querySelector('.images-upload-area').addEventListener('click', function() {
    document.getElementById('shopImagesInput').click();
});
});

    // 处理头像上传
    function handleAvatarUpload(event) {
    const file = event.target.files[0];
    console.log(1)
    if (!file.type.startsWith('image/')) {
    alert('请选择图片文件');
    return;
}

    // 文件大小限制（2MB）
    if (file.size > 2 * 1024 * 1024) {
    alert('图片大小不能超过2MB');
    return;
    };
        const formData = new FormData();
        console.log(33)
        console.log("file是什么"+file)
        formData.append("file", file);  // "file" 必须和后端参数名一致
        $.ajax({
            url: "/upload",  // 替换为你的Servlet URL
            type: "POST",
            data: formData,
            processData: false,      // 禁止jQuery处理数据（文件上传必须）
            contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
            cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
            success: function (response) {
                imgSrc = response.data
                console.log(imgSrc)
                document.getElementById('shopAvatar').src=imgSrc
            },error: function(xhr, status, error) {
                console.error("上传失败:", error);
                $("#result").html("上传失败: " + (xhr.responseText || error));
            }
        });

}

    // 处理店铺图片上传
    function handleShopImagesUpload(event) {
    const files = event.target.files;

    if (files.length > 0) {
    // 检查总图片数量
    if (uploadedImages.length + files.length > 10) {
    alert('最多只能上传10张图片');
    return;
}

    for (let i = 0; i < files.length; i++) {
    const file = files[i];

    if (!file.type.startsWith('image/')) {
    alert('请选择图片文件');
    continue;
}

    // 文件大小限制（5MB）
    if (file.size > 5 * 1024 * 1024) {
    alert(`图片 ${file.name} 大小超过5MB，请重新选择`);
    continue;
}

    const reader = new FileReader();
    reader.onload = function(e) {
        var uploadImg1;
        const formData = new FormData();
        console.log(33)
        console.log("file是什么"+file)
        formData.append("file", file);  // "file" 必须和后端参数名一致
        $.ajax({
            url: "/upload",  // 替换为你的Servlet URL
            type: "POST",
            data: formData,
            processData: false,      // 禁止jQuery处理数据（文件上传必须）
            contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
            cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
            success: function (response) {
                uploadImg1 = response.data
                console.log(uploadImg1)
                uploadedImages.push({
                    file: file,
                    dataUrl: uploadImg1
                });
                updateShopImagesPreview();
            },error: function(xhr, status, error) {
                console.error("上传失败:", error);
                $("#result").html("上传失败: " + (xhr.responseText || error));
            }
        });


};
    reader.readAsDataURL(file);
}

    // 清空input以便再次选择相同文件
    event.target.value = '';
}
}

    // 更新店铺图片预览
    function updateShopImagesPreview() {
    const previewContainer = document.getElementById('shopImagesPreview');
    previewContainer.innerHTML = '';

    uploadedImages.forEach((image, index) => {
    const previewItem = document.createElement('div');
    previewItem.className = 'image-preview-item';
    previewItem.innerHTML = `
        <img src="${image.dataUrl}" alt="店铺图片">
        <button type="button" class="image-remove-btn" onclick="removeShopImage(${index})">
          <i class="bi bi-x"></i>
        </button>
      `;
    previewContainer.appendChild(previewItem);
});
}

    // 删除店铺图片
    function removeShopImage(index) {
    uploadedImages.splice(index, 1);
    updateShopImagesPreview();
}

    // 处理营业执照预览
    function handleLicensePreview(event, previewId) {
    const file = event.target.files[0];
    if (file) {
    if (!file.type.startsWith('image/')) {
    alert('请选择图片文件');
    return;
}

    const reader = new FileReader();
    reader.onload = function(e) {
    const preview = document.getElementById(previewId);
    const formData = new FormData();
    console.log(33)
        console.log("file是什么"+file)
        formData.append("file", file);  // "file" 必须和后端参数名一致
        $.ajax({
            url: "/upload",  // 替换为你的Servlet URL
            type: "POST",
            data: formData,
            processData: false,      // 禁止jQuery处理数据（文件上传必须）
            contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
            cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
            success: function (response) {
                preview.querySelector('img').src = response.data;
                preview.style.display = 'block';

            },error: function(xhr, status, error) {
                console.error("上传失败:", error);
                $("#result").html("上传失败: " + (xhr.responseText || error));
            }
        });

};
    reader.readAsDataURL(file);
}
}

    // 移除营业执照预览
    function removeLicensePreview() {
    const preview = document.getElementById('licensePreview');
    preview.style.display = 'none';
    document.getElementById('businessLicense').value = '';
}

    // 处理其他证书上传
    function handleCertificatesUpload(event) {
    const files = event.target.files;
    if (files.length > 0) {
    for (let i = 0; i < files.length; i++) {
    const file = files[i];

    if (!file.type.startsWith('image/')) {
    alert('请选择图片文件');
    continue;
}

    const reader = new FileReader();
    reader.onload = function(e) {
        var uploadImg1;
        const formData = new FormData();
        console.log(33)
        console.log("file是什么"+file)
        formData.append("file", file);  // "file" 必须和后端参数名一致
        $.ajax({
            url: "/upload",  // 替换为你的Servlet URL
            type: "POST",
            data: formData,
            processData: false,      // 禁止jQuery处理数据（文件上传必须）
            contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
            cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
            success: function (response) {
                uploadImg1 = response.data
                console.log(uploadImg1)

                uploadedCertificates.push({
                    file: file,
                    dataUrl: uploadImg1
                });
                updateCertificatesPreview();
            },error: function(xhr, status, error) {
                console.error("上传失败:", error);
                $("#result").html("上传失败: " + (xhr.responseText || error));
            }
        });

};
    reader.readAsDataURL(file);
}

    // 清空input以便再次选择相同文件
    event.target.value = '';
}
}

    // 更新证书预览
    function updateCertificatesPreview() {
    const previewContainer = document.getElementById('certificatesPreview');
    previewContainer.innerHTML = '';

    uploadedCertificates.forEach((certificate, index) => {
    const previewItem = document.createElement('div');
    previewItem.className = 'image-preview-item';
    previewItem.innerHTML = `
        <img src="${certificate.dataUrl}" alt="证书图片">
        <button type="button" class="image-remove-btn" onclick="removeCertificate(${index})">
          <i class="bi bi-x"></i>
        </button>
      `;
    previewContainer.appendChild(previewItem);
});
}

    // 删除证书
    function removeCertificate(index) {
    uploadedCertificates.splice(index, 1);
    updateCertificatesPreview();
}

    // 表单提交
    document.getElementById('shopApplicationForm').addEventListener('submit', function(e) {
    e.preventDefault();

    // 表单验证
    if (!validateForm()) {
    return;
}

    // 收集表单数据
    const formData = new FormData();

    // 添加基本表单数据
    const formElements = this.elements;
    for (let i = 0; i < formElements.length; i++) {
    const element = formElements[i];
    if (element.name && element.type !== 'file') {
    formData.append(element.name, element.value);
}
}

    // 添加头像
    const avatarInput = document.getElementById('avatarInput');
    if (avatarInput.files.length > 0) {
    formData.append('avatar', avatarInput.files[0]);
}

    // 添加店铺图片
    uploadedImages.forEach((image, index) => {
    formData.append('shopImages', image.file);
});

    // 添加营业执照
    const licenseInput = document.getElementById('businessLicense');
    if (licenseInput.files.length > 0) {
    formData.append('businessLicense', licenseInput.files[0]);
}

    // 添加其他证书
    uploadedCertificates.forEach((certificate, index) => {
    formData.append('certificates', certificate.file);
});
    var avatarUrl = document.querySelector("#shopAvatar").src
        var shopName = document.querySelector("#shopName").value
        var shopCategory = document.querySelector("#shopCategory").value
        var shopDescription = document.querySelector("#shopDescription").value
        var shopAddress = document.querySelector("#shopAddress").value
        // var shopPhone = document.querySelector(/"#shopPhone").value
        // var shopHours = document.querySelector("#shopHours").value
        var realName = document.querySelector("#ownerName").value
        var openTime = document.querySelector("#businessHours").value.split("-")[0]
        var closeTime = document.querySelector("#businessHours").value.split("-")[1]
        const bannerUrls = [];
        const previewContainer = document.getElementById('shopImagesPreview');
        const images = previewContainer.querySelectorAll('.image-preview-item img');

        images.forEach(img => {
            console.log(img.src)
            bannerUrls.push(img.src);
        });
        var businessLicense = document.querySelector("#licensePreview img").src
        const otherDocuments = [];
        const certificatesPreview = document.getElementById('certificatesPreview');
        const certificates = certificatesPreview.querySelectorAll('.image-preview-item img');
        certificates.forEach(img => {
            otherDocuments.push(img.src);
        })
        var longitude;
        var latitude;
        getCoordinatesFromAddress(shopAddress)
            .then(result => {
                console.log('解析结果:', result);
                longitude = result.longitude;
                latitude = result.latitude;
                console.log('经度:', result.longitude);
                console.log('纬度:', result.latitude);
                console.log('完整地址:', result.formattedAddress);
                $.ajax({
                    url:"shopAduit/add",
                    type:"POST",
                    data:{
                        avatarUrl: avatarUrl,
                        name: shopName,
                        tagId: parseInt(shopCategory),
                        desc: shopDescription,
                        openTime: formatTime(openTime),
                        closeTime: formatTime(closeTime),
                        ownerId:parseInt($.cookie("userid")),
                        bannerUrls: JSON.stringify(bannerUrls),
                        businessLicense: businessLicense,
                        longitude: longitude,
                        latitude: latitude,
                        otherDocuments: JSON.stringify(otherDocuments)
                    },
                    success:function(data){
                        console.log(data)
                        location.href="UserOwnerShops"
                    }
                })

            })
            .catch(error => {
                console.error('错误:', error.message);
            });

        var shopData = {
            avatarUrl: avatarUrl,
            name: shopName,
            tagId: parseInt(shopCategory),
            desc: shopDescription,
            openTime: openTime,
            closeTime: closeTime,
            ownerId:parseInt($.cookie("userOwnerId")),
            bannerUrls: JSON.stringify(bannerUrls),
            businessLicense: businessLicense,
            longitude: longitude,
            latitude: latitude,
            otherDocuments: JSON.stringify(otherDocuments)
        }

        // 模拟提交到服务器
    console.log('提交店铺申请数据:', Object.fromEntries(formData));

    // 显示成功模态框
    document.getElementById('successModal').style.display = 'flex';
});

    // 表单验证
    function validateForm() {
    const shopName = document.getElementById('shopName').value.trim();
    const shopCategory = document.getElementById('shopCategory').value;
    const ownerName = document.getElementById('ownerName').value.trim();
    const phone = document.getElementById('phone').value.trim();
    const shopDescription = document.getElementById('shopDescription').value.trim();
    const shopAddress = document.getElementById('shopAddress').value.trim();
    const businessHours = document.getElementById('businessHours').value.trim();
    const businessLicense = document.getElementById('businessLicense').files.length;

    if (!shopName) {
    alert('请输入店铺名称');
    document.getElementById('shopName').focus();
    return false;
}

    if (!shopCategory) {
    alert('请选择店铺分类');
    document.getElementById('shopCategory').focus();
    return false;
}

    if (!ownerName) {
    alert('请输入店主姓名');
    document.getElementById('ownerName').focus();
    return false;
}

    // 手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
    alert('请输入有效的手机号码');
    document.getElementById('phone').focus();
    return false;
}

    if (!shopDescription) {
    alert('请输入店铺简介');
    document.getElementById('shopDescription').focus();
    return false;
}

    if (!shopAddress) {
    alert('请输入店铺地址');
    document.getElementById('shopAddress').focus();
    return false;
}

    if (!businessHours) {
    alert('请输入营业时间');
    document.getElementById('businessHours').focus();
    return false;
}

    if (!businessLicense) {
    alert('请上传营业执照');
    document.getElementById('businessLicense').focus();
    return false;
}

    return true;
}

    // 关闭成功模态框
    function closeSuccessModal() {
    document.getElementById('successModal').style.display = 'none';
    // 可选：跳转到其他页面
    // window.location.href = '/my-shops';
}
function getCoordinatesFromAddress(address) {
    return new Promise((resolve, reject) => {
        const apiKey = '2105ba620f46e78a74b47d937077308a';
        const url = `https://restapi.amap.com/v3/geocode/geo?key=${apiKey}&address=${encodeURIComponent(address)}&output=JSON`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.status === '1' && data.geocodes && data.geocodes.length > 0) {
                    const geocode = data.geocodes[0];
                    const location = geocode.location.split(','); // 经度,纬度

                    resolve({
                        longitude: parseFloat(location[0]),
                        latitude: parseFloat(location[1]),
                        formattedAddress: geocode.formatted_address,
                        province: geocode.province,
                        city: geocode.city,
                        district: geocode.district,
                        township: geocode.township,
                        street: geocode.street,
                        number: geocode.number,
                        citycode: geocode.citycode,
                        adcode: geocode.adcode,
                        level: geocode.level
                    });
                } else {
                    reject(new Error('地址解析失败: ' + (data.info || '未找到对应坐标')));
                }
            })
            .catch(error => {
                reject(error);
            });
    });
}
function formatTime(timeStr) {
    if (!timeStr) return null;

    // 如果已经是完整格式，直接返回
    if (timeStr.includes(':') && timeStr.split(':').length === 3) {
        return timeStr;
    }

    // 补全秒数
    if (timeStr.includes(':') && timeStr.split(':').length === 2) {
        return timeStr + ':00';
    }

    // 如果是纯数字，如 "0900"
    if (/^\d{4}$/.test(timeStr)) {
        return timeStr.substring(0, 2) + ':' + timeStr.substring(2) + ':00';
    }

    return timeStr;
}